package com.quzi.kettle.activitise;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpClient;
import com.quzi.kettle.GlobalConfig;
import com.quzi.kettle.R;
import com.quzi.kettle.activitise.added.ActivityManager;
import com.quzi.kettle.activitise.added.WaterDateUtil;
import com.quzi.kettle.bean.ModeItem;
import com.quzi.kettle.bean.http.KettleDevice;
import com.quzi.kettle.bean.http.User;
import com.quzi.kettle.datapiece.FactoryDataBody;
import com.quzi.kettle.datapiece.status.DeviceStatus;
import com.quzi.kettle.push.Thermometer;
import com.quzi.kettle.utils.ByteUtils;
import com.quzi.kettle.utils.DialogUtil;
import com.quzi.kettle.utils.MSharePerference;

public abstract class BaseActivity extends Activity implements OnClickListener {

	public static final String MODES = "MODES";

	protected static final int TOASTMSG = 1;
	private static final int DISMISS = 2;
	private boolean isShowing = false;
	protected int targetTemperature = 80;// test mode

	private int TIMEOUT = 15000;// MS

	protected boolean TEST_MODE = true;

	protected Handler UIHandler;
	protected Thermometer publisher;
	protected DeviceStatus status = new DeviceStatus();

	protected AsyncHttpClient client = new AsyncHttpClient();

	protected static User currUser;
	protected static KettleDevice currDevice;
	protected static List<KettleDevice> deviceList = new ArrayList<KettleDevice>();

	protected static DeviceStatus modeStatus = new DeviceStatus();

	protected List<ModeItem> getModeList() {
		String str = MSharePerference.getInstance(getApplicationContext()).get(
				MODES);
		List<ModeItem> list = new Gson().fromJson(str,
				new TypeToken<List<ModeItem>>() {
				}.getType());
		if (null == list) {
			list = new ArrayList<ModeItem>();
		}
		return list;
	}

	/**
	 * 多种隐藏软件盘方法的其中一种
	 * 
	 * @param token
	 */
	protected void hideSoftInput() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// 得到InputMethodManager的实例
		if (imm.isActive()) {
			// 如果开启
			imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
					InputMethodManager.HIDE_NOT_ALWAYS);
			// 关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
		}
	}

	protected void sendCommand() {
		if (!TEST_MODE) {
			if (status.test1 != 0) {
				Toast.makeText(getApplicationContext(),
						getResources().getString(R.string.toastmessage),
						Toast.LENGTH_LONG).show();
			} else {
				byte[] result = FactoryDataBody.createFactoryDataBody(
						FactoryDataBody.REQUEST, status).toBytes();
				publisher.sendControlText(result);
				Log.d("mmqtt", "sendCommand   "
						+ status.setFixedTemperatureTime + "  "
						+ status.get_rid_cl_work);
				String request = ByteUtils.printHexString(result);
				Log.d("mmqtt", "request = " + request);
				if (!isShowingDialog()) {
					Log.v("dialog", " i am int he dialog showing");
					showLoadingDialog();
				} else {
					Log.v("dialog", " i am inthe dialog   dounot showing");
				}
			}
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ActivityManager.getInstance().addActivity(this);
		UIHandler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				// TODO Auto-generated method stub
				super.dispatchMessage(msg);
				switch (msg.what) {
				case TOASTMSG:
					Log.v("Water", "not water  TOASTMSG");
					Toast.makeText(getApplicationContext(), (String) msg.obj,
							Toast.LENGTH_SHORT).show();
					break;
				case DISMISS:
					if (isShowingDialog()) {
						UIHandler.obtainMessage(TOASTMSG, "操作超时")
								.sendToTarget();
						dissLoadingDialog();
					}
					break;
				}
			}
		};

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		ActivityManager.getInstance().removeActivity(this);
	}

	private Toast toast = null;

	public void showTextToast(String msg) {
		if (toast == null) {
			toast = Toast.makeText(getApplicationContext(), msg,
					Toast.LENGTH_SHORT);
		} else {
			toast.setText(msg);
		}
		toast.show();
	}

	protected void nextActivity(Class activityClass) {
		Intent intent = new Intent(this, activityClass);
		startActivity(intent);

	}

	protected void initTitleBar() {

	}

	public void showLoadingDialogWithTimeOut() {
		isShowing = true;
		DialogUtil.showProgressDialog(this);
	}

	public void disLoadingDialogWithTimeOut() {
		isShowing = false;

		DialogUtil.hideProgressDialog();

	}

	public void showLoadingDialog() {
		isShowing = true;
		UIHandler.sendEmptyMessageDelayed(DISMISS, TIMEOUT);
		DialogUtil.showProgressDialog(this);
	}

	public void dissLoadingDialog() {
		isShowing = false;
		UIHandler.removeMessages(DISMISS);
		DialogUtil.hideProgressDialog();

	}

	public boolean isShowingDialog() {

		return isShowing;
	}

	public String getTopic() {
		return MSharePerference.getInstance(getApplicationContext()).get(
				GlobalConfig.MAC);
	}

	public void setTopic(String str) {
		MSharePerference.getInstance(getApplicationContext()).update(
				GlobalConfig.MAC, str);
	}

	public String getTargetURL(int target) {
		String result = GlobalConfig.mUrl + GlobalConfig.map.get(target);
		return result;
	}

	protected AlertDialog dialog;

	protected void showDialog(Activity clazz, View view) {
		dialog = new AlertDialog.Builder(clazz).setView(view).create();
		dialog.show();
	}

}
